package com.nice.tcp;

import org.apache.log4j.Logger;

import com.nice.main.Bootstart;
import com.nice.message.MessageCodec;
import com.nice.service.Service;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class TCPService implements Runnable, Service {

	private static Logger log = Logger.getLogger(MessageCodec.class);
	private NioEventLoopGroup bossGp;
	private NioEventLoopGroup worker;
	private int port;

	public TCPService(int port) {
		this.port = port;
	}

	public void start(Bootstart bt) {
		log.info("server is running:" + port);
		new Thread(this).start();
	}

	@Override
	public void run() {
		bossGp = new NioEventLoopGroup();
		worker = new NioEventLoopGroup(4);
		try {
			ServerBootstrap bt = new ServerBootstrap();
			bt.group(bossGp, worker);
			bt.channel(NioServerSocketChannel.class);
			bt.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel chanel)
						throws Exception {
					ChannelPipeline pipeline = chanel.pipeline();
					pipeline.addLast(new MessageCodec());
					pipeline.addLast(new NettyMsgHandler());
					pipeline.addLast(new MessageCodec());
				}

			});
			bt.bind(port).sync().channel().closeFuture().awaitUninterruptibly();
		} catch (InterruptedException e) {
			throw new RuntimeException("fail to  start tcp server", e);
		} finally {
			bossGp.shutdownGracefully();
			worker.shutdownGracefully();
		}
	}

	@Override
	public void stop(Bootstart bt) {
		bossGp.shutdownGracefully();
		worker.shutdownGracefully();
	}

}
